#include "Gkey_board_sample.h"

struct key_pin_t {
    GPIO_TypeDef *port;
    uint16_t pin;
    uint8_t valid;
    uint8_t invalid;
};

const struct key_pin_t key_pin_sig[] = {
    {
        .port = KEY1_PORT,
        .pin = KEY1_PIN,
        .valid = KEY1_PRESS_LEVEL,
        .invalid = KEY1_RELEASE_LEVEL
    },
    {
        .port = KEY2_PORT,
        .pin = KEY2_PIN,
        .valid = KEY2_PRESS_LEVEL,
        .invalid = KEY2_RELEASE_LEVEL
    },
		{
        .port = KEY3_PORT,
        .pin = KEY3_PIN,
        .valid = KEY3_PRESS_LEVEL,
        .invalid = KEY3_RELEASE_LEVEL
    },
		{
        .port = KEY4_PORT,
        .pin = KEY4_PIN,
        .valid = KEY4_PRESS_LEVEL,
        .invalid = KEY4_RELEASE_LEVEL
    }
};



static inline bool pin_level_get(const void *desc)
{
    struct key_pin_t *pdesc;

    pdesc = (struct key_pin_t *)desc;
    return GPIO_ReadInputDataBit(pdesc->port, pdesc->pin) == pdesc->valid;
}

const struct key_public_sig_t key_public_sig[] = {
    KEY_PUBLIC_SIG_DEF(KEY1, &key_pin_sig[0], pin_level_get, KEY_FLAG_PRESS_CONTINUOUS | KEY_FLAG_PRESS_LONG | KEY_FLAG_RELEASE_LONG | KEY_FLAG_PRESS_MULTI | KEY_FLAG_RELEASE_MULTI),
    KEY_PUBLIC_SIG_DEF(KEY2, &key_pin_sig[1], pin_level_get, KEY_FLAG_PRESS_CONTINUOUS | KEY_FLAG_PRESS_LONG | KEY_FLAG_RELEASE_LONG | KEY_FLAG_PRESS_MULTI | KEY_FLAG_RELEASE_MULTI),
    KEY_PUBLIC_SIG_DEF(KEY3, &key_pin_sig[2], pin_level_get, KEY_FLAG_PRESS_CONTINUOUS | KEY_FLAG_PRESS_LONG | KEY_FLAG_RELEASE_LONG | KEY_FLAG_PRESS_MULTI | KEY_FLAG_RELEASE_MULTI),
    KEY_PUBLIC_SIG_DEF(KEY4, &key_pin_sig[3], pin_level_get, KEY_FLAG_PRESS_CONTINUOUS | KEY_FLAG_PRESS_LONG | KEY_FLAG_RELEASE_LONG | KEY_FLAG_PRESS_MULTI | KEY_FLAG_RELEASE_MULTI),
};



/*按键 GPIO 初始化*/
void GPIO_Key_Board_Init(void)
{

	//1、开启时钟
  	RCC_KEY_BOARD_CLK_ENABLE();

		//2、GPIO初始化
		GPIO_InitTypeDef gpio;
		gpio.GPIO_Mode = GPIO_Mode_IN;  //设置为输入模式
		gpio.GPIO_PuPd = GPIO_PuPd_UP;   //上拉
		gpio.GPIO_Speed = GPIO_Medium_Speed;  //中速
    for(int i = 0;i < GET_ARRAY_SIZE(key_pin_sig);i++)
    {
        gpio.GPIO_Pin   = key_pin_sig[i].pin;
        GPIO_Init(key_pin_sig[i].port, &gpio);
    }

    key_board_init();
    key_board_register(KEY_BOARD_NORMAL, key_public_sig, GET_ARRAY_SIZE(key_public_sig), NULL, 0);
}
